const fs = require('fs-extra');
const path = require('path');
// const rename = think.promisify(fs.rename, fs);

const BaseRest = require('./base.js');

module.exports = class extends BaseRest {
  async getAction() {
    let data;
    const map = {};

    if (this.id) {
      data = this.modelInstance.where({
        id: this.id
      }).field('id,base_url,path').find();
      return this.success(data);
    }

    // 关键词
    const key = this.get('key');
    if (key) {
      map['path'] = ['like', '%' + key + '%'];
    }

    // 页码
    const page = this.get('page') || 1;
    // 每页显示数量
    const pageSize = this.get('pageSize') || 5;

    think.logger.debug(map);

    data = await this.modelInstance.where(map).page(page, pageSize).order('id desc').countSelect();
    return this.success(data);
  }

  // 图片上传
  async postAction() {
    think.logger.error(this.post());

    const storage = this.post('storage') || 'local';

    switch (storage.toLowerCase()) {
      case 'local':
        const file = this.file('file'); // 七牛云单一文件上传必须使用token,file作为key
        if (!file) {
          return this.fail(1000, '请上传文件');
        }

        // 计算md5校验值，如果相同则不保存新的
        const buf = await fs.readFile(file.path);
        const checksum_md5 = think.md5(buf);

        let data;
        if (await this.modelInstance.where({
          md5: checksum_md5
        }).count() > 0) {
          // 文件已经存在
          data = this.modelInstance.where({
            md5: checksum_md5
          }).field('id,base_url,path').find();
          return this.success(data, '上传文件已经存在，使用已经存在的文件。');
        }

        // 文件不存在
        // path.extname获取文件后缀名，可做上传控制
        const extname = path.extname(file.name);
        const filename = path.basename(file.path);
        const basename = think.md5(filename) + extname;
        const date = new Date();
        const year = date.getFullYear();
        const month = (date.getMonth() + 1) < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1);
        const savepath = '/uploads/' + year + '/' + month + '/' + basename;
        const filepath = path.join(think.ROOT_PATH, 'www' + savepath);

        think.mkdir(path.dirname(filepath));
        await fs.rename(file.path, filepath);

        const row = await this.model('config').where({
          name: 'site'
        }).find();
        const config = JSON.parse(row.value);

        data = {
          base_url: config.url,
          path: savepath
        };
        // let data={base_url:config.url, path: savepath, basename:basename, filepath:filepath};
        const id = await this.modelInstance.add({
          ...data,
          storage: 'local',
          md5: checksum_md5,
          create_time: Math.round((new Date()).getTime() / 1000)
        });
        data.id = id;
        await this.hook('upload', data);
        // delete data.filepath;
        return this.success(data, '上传成功');

      case 'qiniu':
      {
        const data = this.post();

        const id = await this.modelInstance.add({
          ...data,
          storage: 'qiniu',
          // md5: checksum_md5,
          create_time: Math.round((new Date()).getTime() / 1000)
        });
        data.id = id;
        await this.hook('upload', data);
        // delete data.filepath;
        return this.success(data, '上传成功');
      }
    }
  }
};
